package com.sunlee.common.core.utils;

import com.sunlee.common.core.entity.PageData;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 自定义List分页工具
 *
 * @author sunlee
 */
public class CustomizePageUtil {

    private CustomizePageUtil() {

    }

    /**
     * 开始分页
     *
     * @param list     需分页的集合
     * @param pageNum  页码
     * @param pageSize 每页多少条数据
     * @return 分页后的集合
     */
    public static <T> PageData<T> startPage(List<T> list,
                                            Long pageNum,
                                            Long pageSize) {

        if (CollectionUtils.isEmpty(list)) {
            return new PageData<>(list, 0);
        }

        if (pageNum == null) {
            pageNum = 1L;
        }
        if (pageSize == null) {
            pageSize = 10L;
        }

        // 总数
        long total = list.size();
        // 页数
        long pageCount;

        if (total % pageSize == 0) {
            pageCount = total / pageSize;
        } else {
            pageCount = total / pageSize + 1;
        }

        // 开始索引
        long fromIndex;
        // 结束索引
        long toIndex;

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = total;
        }

        return new PageData<>(list.subList((int) fromIndex, ((int) toIndex)), list.size());
    }

}